package com.user.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.ResultCode;
import com.user.config.Exception.ServiceExceptionUtil;
import com.user.dao.SysRoleMenuDao;
import com.user.entity.SysRole;
import com.user.entity.SysRoleMenu;
import com.user.service.IRole;
import com.user.service.IRoleMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: Member_Perks_Store
 * @description: 角色菜单服务
 * @author: 无恙
 * @create: 2024-06-17 12:45
 **/

@Service
public class IRoleMenuImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenu> implements IRoleMenu {

    private  SysRoleMenuDao roleMenuDao;

    private IRole IRole;

    @Autowired
    public void setRoleMenuDao(SysRoleMenuDao roleMenuDao) {
        this.roleMenuDao = roleMenuDao;
    }

    @Autowired
    public void  setIRole(IRole IRole) {
        this.IRole = IRole;
    }

    @Override
    public List<String> getPermissionByUid(Long uid) {
        //获取角色
       final List<Long> Ids = IRole.getByUid(uid)
                .stream().map(SysRole::getId).collect(Collectors.toList());
        QueryWrapper<SysRoleMenu> roleId = new QueryWrapper<SysRoleMenu>().in("role_id", Ids);
        //获取相应权限码
        List<String> permissions = roleMenuDao.selectList(roleId)
                .stream().map(sm ->
                        sm.getPermissionCode().split(",")
                ).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
        //为空，数据返回异常
        if(permissions.isEmpty()) {
            throw ServiceExceptionUtil.exception(ResultCode.DEFAULT_DATA_NOT_EXISTS);
        }

        return permissions;
    }
}
